import { observable, action, computed, toJS } from "mobx";
import { message, Modal } from 'antd';
import { fillinTypes, appStatus, DESIGN_URL } from "../constants/app";
import { WeaForm } from 'comsMobx';
import _action, { shareList, deleteShare } from "../apis/app";
import TASKAPI from '../apis/task';
import ExcelAPI from '../apis/excel';
import route from "../constants/route";
import { createCondition, createDay } from "./task/newTaskCondition";

import { WeaTableNew } from 'comsMobx'
const { TableStore } = WeaTableNew;
import '../components/list/card/index.less'
import { WeaTools, WeaLocaleProvider } from "ecCom";
import { ExcelPageViewStore } from "./task";
import PathDesignerStore from "./PathDesignerStore";

const { INPUT } = WeaTools.types;
const getLabel = WeaLocaleProvider.getLabel;

const { ALL, FREE, MULTI } = fillinTypes;
const { UNKNOWN, DELETE, EDIT, NEW } = appStatus;

export default class AppManageStore {
  @observable loading = false; // WeaTop loading
  @observable spinning = false; // Spin spinning
  @observable status = UNKNOWN; // 应用操作状态 编辑 删除 新建 
  // @observable apps = []; // 填报的应用
  @observable counts = []; // 应用计数
  @observable selectedType = ALL; // 选中的应用类型
  @observable types = []; // 应用类型
  @observable searchText = ''; // 应用搜索关键字
  @observable editableApp = {}; // 编辑状态的应用
  @observable appids = []; // 选中的应用ids

  @observable newTaskDialogVisible = false;
  @observable newTaskSubmiting = false;
  @observable newTaskApp = {};
  @observable newTaskFrom = new WeaForm();

  @observable publishDialogVisible = false;
  @observable publishApp = {};
  @observable baseDateHide = true;

  // 共享
  @observable shareDialogVisible = false;
  @observable shareListVisible = false;
  @observable shareListType = 'default';
  @observable shareListTableStore = new TableStore();
  @observable shareForm = new WeaForm();
  @observable shareApp = {};


  @observable createRight = false;//新建权限
  @observable modifyRight = false;//维护权限
  @observable canCreated = false;//再创建权限
  @observable createType = '';//创建类型（Excel/Form）

  //@observable total = 0;
  @observable current = 1;
  @observable pageSize = 20;

  @observable tableStore = new TableStore();
  @observable sessionkey = '';
  @observable selectedGroupType = '-2'; // 选中的分组
  @observable firstGroup = '-1';
  @observable searchValue = ''; // 检索值
  @observable leftDatas = [];
  @observable appGroupFrom = new WeaForm();
  @observable newAppGroupDialogVisible = false;
  @observable newAppGroup = {};
  @observable notMine;

  @observable disableAll = false;

  @observable copyAppDialogVisible = false;
  @observable copyAppForm = new WeaForm();
  @observable copyAppSubmiting = false;
  @observable copyAppProgress = 0;
  @observable copyAppId = '';
  @observable excelPageViewStore = new ExcelPageViewStore();
  @observable pathDesignerStore = new PathDesignerStore();
  @observable excelPages = [];
  @observable selectedPage = '';
  @observable readonly = false;

  @computed get newTaskDialog() {
    return {
      visible: this.newTaskDialogVisible,
      app: this.newTaskApp,
      onCancel: this.hideNewTaskDialog,
      submiting: this.newTaskSubmiting,
      form: this.newTaskFrom,
      onSave: this.saveTask,
      showDesigner: this.showDesigner,
    }
  }

  @computed get newAppGroupDialog() {
    return {
      visible: this.newAppGroupDialogVisible,
      app: this.AppGroup,
      onCancel: this.hideNewAppGroupDialog,
      submiting: this.newTaskSubmiting,
      form: this.appGroupFrom,
      onSave: this.saveGroupApp
    }
  }

  @computed get shareDialog() {
    return {
      visible: this.shareDialogVisible,
      onCancel: this.hideShareDialog,
      title: `${getLabel('513429', '共享：')}${this.shareApp.name}`,
      onOk: this.saveShareApp,
    }
  }

  @computed get copyAppDialog() {
    return {
      visible: this.copyAppDialogVisible,
      onSave: this.copyApp,
      onCancel: this.hideCopyAppDialog,
      form: this.copyAppForm,
      submiting: this.copyAppSubmiting,
      progress: this.copyAppProgress
    }
  }
  @action openCopyAppDialog = (app) => {
    if(this.copyAppSubmiting) {
      message.error("有应用正在复制，请稍后")
      return;
    }
    this.copyAppProgress = 0;

    this.copyAppDialogVisible = true;
    this.copyAppForm = new WeaForm();
    this.copyAppForm.setCondition([{
      items: [{
        conditionType: INPUT,
        domkey: ["id"],
        label: 'id',
        hide: true
      }, {
        conditionType: INPUT,
        domkey: ["appName"],
        rules: 'required',
        label: getLabel(381923, '应用名称'),
        viewAttr: 3
      }],
      defaultshow: true
    }]);
    this.copyAppForm.updateFields({
      id: { value: (app || {}).id || "" }
    });
  }
  @action hideCopyAppDialog = () => {
    this.copyAppDialogVisible = false;
  }
  @action copyApp = () => {
    this.copyAppForm.validateForm().then(f => {
      if (!f.isValid) {
        f.showErrors();
        return;
      }
      const formData = this.copyAppForm.getFormParams();
      const { id, appName } = formData;
      this.copyAppForm.setField("appName", { viewAttr: 1, hasBorder: true })
      this.copyAppForm.updateFields({ appName: { value: appName } });

      this.copyAppSubmiting = true;
      const getProgress = setInterval(() => {
        if(this.copyAppProgress===99) {
          clearInterval(getProgress);
          return;
        }
        this.copyAppProgress += 1;
      }, 100);

      _action.copyApp({ id, appName }).then(result => {
        clearInterval(getProgress);
        this.copyAppProgress = 100;
        this.copyAppSubmiting = false;
        this.copyAppId = result.copyAppId;
        this.getApps();
        if (result&&result.appList) this.setLeftData(result.appList);
      }).catch((e) => {
        clearInterval(getProgress);
        this.copyAppSubmiting = false;
        this.copyAppDialogVisible = false;
      });

    })
  }

  @computed get groupTypes() {
    const types = this.leftDatas.filter(d => (d.groupName.toLowerCase().indexOf((this.searchValue || '').toLowerCase()) > -1) ||
      (d.creator.toLowerCase().indexOf((this.searchValue || '').toLowerCase()) > -1));

    return types;
  }

  @computed get myGroups() {
    return this.leftDatas.map(s => ({ key: s.id + '', showname: s.groupName, selected: s.isdefault == '1' }));
  }

  @computed get myGroupTypes() {
    return this.leftDatas.filter(d => d.notMine !== '1' && ((d.groupName.toLowerCase().indexOf((this.searchValue || '').toLowerCase()) > -1)
      || (d.creator.toLowerCase().indexOf((this.searchValue || '').toLowerCase()) > -1)));
  }
  @computed get shareGroupTypes() {
    return this.leftDatas.filter(d => d.notMine === '1' && ((d.groupName.toLowerCase().indexOf((this.searchValue || '').toLowerCase()) > -1)
      || (d.creator.toLowerCase().indexOf((this.searchValue || '').toLowerCase()) > -1)));
  }
  @computed get shareDeleteDisabled() {
    return this.shareListTableStore.selectedRowKeysAllPages.slice().length === 0;
  }
  @action saveTask = () => {
    this.newTaskFrom.validateForm().then(f => {
      if (!f.isValid) {
        f.showErrors();
        return;
      }
      this.newTaskSubmiting = true;
      const formdata = this.newTaskFrom.getFormParams();
      TASKAPI.saveTask(formdata).then((result) => {
        this.newTaskSubmiting = false;
        this.hideNewTaskDialog();
        if (result) {
          if (!result.hasExcel) {
            message.error(getLabel('511903', '新建任务失败,该应用未创建表格'));
          }
        } else {
          message.success(getLabel('505987', '新建任务成功'));
        }
      });

    });
  }

  @action deleteGroupApp = () => {

  }

  @action saveGroupApp = () => {
    this.appGroupFrom.validateForm().then(f => {
      if (!f.isValid) {
        f.showErrors();
        return;
      }
      this.newTaskSubmiting = true;
      const formdata = this.appGroupFrom.getFormParams();
      TASKAPI.saveAppGroup(formdata).then((result) => {
        this.newTaskSubmiting = false;
        this.hideNewAppGroupDialog();
        if (result) {
          if (result.error) {
            message.error(result.error);
          } else {
            if (formdata.id) {

              message.success(getLabel('511904', '修改分组名称成功'));
            } else {

              message.success(getLabel('511905', '新建分组成功'));
            }
          }
          if (result.groupList) {
            this.setLeftData(result.groupList);
          }

        }
      });

    });
  }

  @action deleteAppGroup = (menu) => {
    Modal.confirm({
      title: getLabel('511906', '删除分组'),
      content: getLabel('511907', '确认要删除该分组？'),
      onOk: () => {
        TASKAPI.deleteAppGroup({ id: menu.id })
          .then((result) => {
            if (result) {
              if (result.error) {
                message.error(result.error);
              } else {
                message.success(getLabel('511908', '删除分组成功'));
                if (menu.id == this.selectedGroupType) {

                  if (result.groupList && result.groupList.length > 0) {
                    this.changeSelectedGroupType(result.groupList[0].id);
                  } else {

                    this.changeSelectedGroupType(this.firstGroup);
                  }

                }
              }
              if (result.groupList) {
                this.setLeftData(result.groupList);
              }

            }
          }
          );
      }
    });
  }

  @action onNewTask = (app) => {
    this.showNewTaskDialog(app);
  }

  @action checkCreateMaxNum = () => {
    _action.checkCreateMaxNum().then((res) => {
      if (res) {
        const right = res.right;
        const createType = res.createtype;
        if (right == '1') {
          this.canCreated = true;
          this.createType = createType;
        } else {
          this.canCreated = false;
          this.createType = "";
        }
      }

      this.onStatusChange(NEW);
    })
  }
  @action hideShareDialog = () => {
    this.shareDialogVisible = false;
  }
  @action saveShareApp = (share) => {
    _action.share({ appid: this.shareApp.id, ...share }).then(() => {
      message.success(getLabel('511909', '共享成功'));
      this.hideShareDialog();
      this.reloadTable();
    });
  }
  @action showShareDialog = (app) => {
    this.shareApp = app;
    this.shareListVisible = true;
    shareList(this.shareApp.id).then(data => {
      this.shareListTableStore.getDatas(data.datas);
      this.disableAll = data.disableAll;
    });
  }
  @action addShare = () => {
    this.shareDialogVisible = true;
  }
  @action deleteShare = () => {
    const _this = this;
    Modal.confirm({
      content: getLabel('505984', '是否确认删除？'),
      onOk() {
        deleteShare(_this.shareListTableStore.selectedRowKeysAllPages.slice().join(','), _this.shareApp.id).then(() => {
          _this.reloadTable();
          message.success(getLabel('505985', '删除成功'));
        });
      },
      onCancel() { },
    });
  }
  @action hideShareList = () => {
    this.shareApp = {};
    this.shareDialogVisible = false;
    this.shareListVisible = false;
  }
  @action changeShareListType = (key) => {
    this.shareListType = key;
  }
  @action reloadTable = () => {
    this.shareListTableStore.reloadCurrent();
  }
  @action onCheck = (checked, app) => {
    const appid = app.id;

    if (checked) {
      this.appids.push(appid);
    } else {
      const index = this.appids.findIndex(id => id === appid);

      this.appids.splice(index, 1);
    }
  }
  @action deleteSingle = (app) => {
    return _action.delete(app.id).then((res) => {
      this.getApps();
      if (res) {
        this.setLeftData(res);
      }
    });
  }
  @action onDelete = () => {
    const ids = this.appids.join(',');
    this.onStatusChange(DELETE);
    return _action.delete(ids).then((data) => {
      this.getApps();
      if (data) {
        this.setLeftData(data);
      }
      this.appids = [];
      this.status = UNKNOWN;
    });
  }

  @action showPublishDialog = app => {
    this.publishApp = app;
    this.publishDialogVisible = true;
  }

  @action hidePublishDialog = app => {
    this.publishApp = {};
    this.publishDialogVisible = false;
  }

  @action showNewTaskDialog = (app) => {
    createDay();
    this.newTaskSubmiting = false;
    this.newTaskFrom.setCondition(createCondition(true, 0, app.operatorSetType));
    this.newTaskFrom.updateFields({
      appid: { value: app.id },
      appName: { value: app.name },
      name: { value: '' },
      cycle: { value: '0' },
      rootOperator: { value: '' }
    });
    this.baseDateHide = true;
    this.newTaskDialogVisible = true;
    this.newTaskApp = app;
    this.rightLevel = app.rightLevel;
    this.readonly = this.rightLevel === '1';
    ExcelAPI.getExcelPages(app.id).then(pages => {
      this.excelPages = pages;
      const parent = { app, excelPages: pages };
      this.pathDesignerStore.parent = () => parent;
    });
  }

  @action onChangeTab = (selectedTab) => {
    this.selectedTab = selectedTab;
    if (this.selectedTab === 'page') {
      if (!this.selectedPage) {
        this.selectedPage = (this.excelPages[0] || {}).id;
      }
      if (this.selectedPage) {
        this.excelPageViewStore.init({ pageid: this.selectedPage });
      }
    } else {
      this[`init${selectedTab}`]();
    }
  }

  @action initpath = () => {
    this.loading = true;
    this.pathDesignerStore.initPath({ appid: this.newTaskApp.id }, this.readonly);
    this.loading = false;
  }

  @action initbaseinfo = () => {
    TASKAPI.getAppPathid({
      "appid": this.newTaskApp.id
    }).then((data) => {
      this.newTaskApp = { operatorSetType: data.operatorSetType, ...this.newTaskApp }
      this.newTaskFrom.setCondition(createCondition(true, 0, data.operatorSetType));
      if (data.operatorSetType != 1) {
        this.newTaskFrom.updateFields({
          rootOperator: { value: '' }
        });
      }
    })
  }

  @action onChangePage = (pageid) => {
    this.selectedPage = pageid;
    this.excelPageViewStore.init({ pageid: this.selectedPage });
  }

  @action updateCondition = (bool, cycle) => {
    this.baseDateHide = bool;
    this.newTaskFrom.setCondition(createCondition(bool, cycle));
    this.newTaskFrom.updateFields({
      cycle: { value: cycle }
    });
  }

  @action hideNewTaskDialog = () => {
    this.newTaskDialogVisible = false;
    this.pathDesignerStore = new PathDesignerStore();
    this.excelPageViewStore = new ExcelPageViewStore();
    this.selectedPage = '';
  }

  @action hideNewAppGroupDialog = () => {
    this.newAppGroupDialogVisible = false;
    this.newAppGroup = {};
  }

  @action init = () => {
    this.loading = true;
    Promise.all([
      this.getLeftDatas()
    ]).then(() => {
      this.loading = false;
    });
  }

  @action
  changeSelectedGroupType = (selectedGroupType) => {
    this.checkIsMine(selectedGroupType);
    this.searchText = '';
    this.selectedGroupType = selectedGroupType;
    this.current = 1
    this.getApps();
  }


  @action
  checkIsMine = (selectedGroupType) => {
    this.notMine = ((this.leftDatas.filter(d => d.id == selectedGroupType)[0]) || {}).notMine;
  }

  @action getAppPathid = (app) => {
    TASKAPI.getAppPathid({
      "appid": app.id
    }).then((data) => {
      const hasPath = data.hasPath;
      const operatorSetType = data.operatorSetType;
      if (hasPath) {
        app.operatorSetType = operatorSetType;
        this.onNewTask(app);
      } else {
        message.error(getLabel('505956', '未设置路径，请先设置路径'));
      }
    })
  }

  @action changePage = (page) => {
    this.appids = [];
    this.current = page;
    this.tableStore.getDatas(this.sessionkey, page, this.pageSize);
  }
  @action changePageSize = (current, pageSize) => {
    this.current = 1;
    this.pageSize = pageSize;
    this.tableStore.getDatas(this.sessionkey, this.current, pageSize);
  }

  @computed get apps() {
    return this.tableStore.datas;
  }

  @computed get total() {
    return this.tableStore.count;
  }

  getApps() {
    this.spinning = true;
    const selectedType = this.selectedType;
    const searchText = this.searchText;
    this.appids = [];
    return _action.getApps({ selectedType, searchText, groupid: this.selectedGroupType }).then(result => {
      this.sessionkey = result.sessionkey.datas;
      this.tableStore.getDatas(this.sessionkey, this.current, this.pageSize);

      //判断创建权限、维护权限
      this.createRight = result.createRight;
      this.modifyRight = result.modifyRight;
      // 是否达到最大创建数（false为已达上限，不能再创建）
      this.canCreated = result.canCreated;

      this.counts = {
        [ALL]: result.allLen,
        [FREE]: result.freeLen,
        [MULTI]: result.multiLen
      };
      this.spinning = false;
    });
  }

  @action getLeftDatas = () => {
    _action.getLeftDatas().then((data) => {
      this.setLeftData(data);
      this.getApps();
    });

  }
  @action
  setLeftData = (data) => {
    this.leftDatas = data;
    if (data.length > 0) {
      this.firstGroup = data[0].id + '';
      if (this.selectedGroupType == '-2')
        this.selectedGroupType = this.firstGroup;

    }

  }

  @action onSelectedTypeChange = selectedType => {
    this.selectedType = selectedType;
    this.current = 1
    this.getApps();
  }

  @action onSearchTextChange = searchText => {
    this.searchText = searchText;
    this.current = 1
    this.getApps();
  }

  @action onStatusChange = status => {
    this.status = status;
  }

  @action onTypesChange = types => {
    types = types.map(({ name, face }) => {
      return {
        key: name,
        title: face,
        showcount: true
      }
    });

    types.unshift({ key: ALL, title: getLabel('507383', '全部'), showcount: true });

    this.types = types;
  }

  @action onEditableAppChange = (editableApp = {}) => {
    this.editableApp = editableApp;
  }

  @action hideDialog = () => {
    this.onStatusChange(UNKNOWN);
    this.onEditableAppChange();
  }

  @action showNewDialog = () => {

    this.checkCreateMaxNum();
  }

  @action exportApp = () => {
    const ids = this.appids.join(',');
    this.spinning = true;
    WeaTools.callApi('/api/edc/app/exportApp', 'GET', { appids: ids }).then(data => {
      this.spinning = false;
      if (data.data.status) {
        //WeaTools.downloadFile(data.data.url + "?download=1", "GET");
        window.location.href = data.data.downurl;
      }
    });
  }

  @action getShowListDatas = (status) => {
    console.log("上传", status);
    if (status == "uploading") {
      this.spinning = true;
    } else if (status == "uploaded") {
      this.spinning = false;
      message.success(getLabel('511910', '导入应用成功'));
      this.getLeftDatas();
    } else if (status == "error") {
      this.spinning = false;
      console.log("上传失败。。。提示下")
      this.getLeftDatas();
    } else {
      this.spinning = false;
    }
  }

  @action showEditDialog = app => {
    this.onStatusChange(EDIT);
    this.onEditableAppChange(app);
  }

  @action onNewOrEdit = (app, hasNotModify) => {
    if (hasNotModify) return this.hideDialog();

    const isEdit = !!app.id;
    const method = isEdit ? 'edit' : 'create';
    _action[method](app).then((res) => {
      this.hideDialog();
      this.getApps();
      if (res) {
        this.setLeftData(res);
      }
    });
  }

  showDesigner = (app) => {
    window.open(`${DESIGN_URL}#/${route.designer}/${app.id}`);
  }
  showData = (app) => {
    window.open(`${DESIGN_URL}#/${route.data}?appid=${app.id}`);
  }

  @action setLeftSearchValue = (value) => {
    this.searchValue = value;
  }

  @action showAppGroupDialog = (app) => {
    this.newTaskSubmiting = false;
    this.appGroupFrom.setCondition([{
      items: [{
        conditionType: INPUT,
        domkey: ["id"],
        label: 'id',
        hide: true
      }, {
        conditionType: INPUT,
        domkey: ["groupName"],
        rules: 'required',
        label: getLabel('506105', '名称'),
        viewAttr: 3
      }],
      defaultshow: true
    }]);
    this.appGroupFrom.updateFields({
      groupName: { value: (app || {}).groupName || "" },
      id: { value: (app || {}).id || "" }
    });
    this.newAppGroupDialogVisible = true;
    this.newAppGroup = app;
  }
}